package com.crt.nexus.security.component;

import com.crt.nexus.core.constant.CommonConstants;
import com.crt.nexus.core.exception.ServiceException;
import com.crt.nexus.core.response.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 客户端异常处理
 * 可以根据 AuthenticationException 不同细化异常处理
 */
@Slf4j
@RequiredArgsConstructor
public class ResourceServerExceptionEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        log.error("授权失败: {}, url: {}", authException.getLocalizedMessage(), request.getRequestURI());
        response.setCharacterEncoding(CommonConstants.UTF8);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        R<String> result = new R<>();
        result.setCode(CommonConstants.FAIL);
        result.setMsg(ServiceException.AUTHENTICATION);
        PrintWriter printWriter = response.getWriter();
        printWriter.print(objectMapper.writeValueAsString(result));
        printWriter.flush();
        printWriter.close();
    }

}
